package com.stars.empoly.vmodel

import android.app.Activity
import android.app.Application
import android.widget.LinearLayout
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hwangjr.rxbus.RxBus
import com.stars.empoly.activity.AddressActivity
import com.stars.empoly.config.ConfigRx
import com.stars.empoly.config.MIntentAction
import com.stars.empoly.inte.ChoiceData
import com.stars.empoly.utils.PopuTipsUtils
import com.stars.empoly.utils.net.NetEngine
import com.trailer.base.base.BRRepository
import com.trailer.base.base.BRViewModel
import com.trailer.base.net.IResp
import com.trailer.base.utils.UiSwitch
import kotlinx.coroutines.launch

/**
 *
 *on 2020/9/25
 */
class AddressListVModel(application: Application) : BRViewModel<BRRepository>(application) {

    var type:String?="-1"

    var ll:LinearLayout?=null

    var position=MutableLiveData<Int>()
    var defautIndex=MutableLiveData<Int>()

    fun toAdd(){//添加地址

        UiSwitch.singleRes(repository().context as Activity,
            AddressActivity::class.java, MIntentAction.REQUEST_CODE_TWO)

    }

    fun toSetDefault(id:String?,index:Int?,isDefault:Int?){//设置默认地址

        if(isDefault==1){
            toast("已经是默认地址，无须设置！")
            return
        }
        viewModelScope.launch {
            var it=repository().lreq { NetEngine.service.setDefault(id) }
            if(it.ok(true)){
                defautIndex.value=index
            }
        }





    }


    fun toDelete(id:String?,index:Int?){

        //删除
        PopuTipsUtils.show(repository().context!!,"确定删除改地址么？",ll!!,object :ChoiceData{
            override fun onRestuse(content: String?) {

                viewModelScope.launch {
                    var it=repository().lreq { NetEngine.service.memberAddressDel(id) }

                    if(it.ok(true)){
                        position.value=index
                        //发送消息
                        RxBus.get().post(ConfigRx.DELETE_ADDRESS, "")

                    }
                }



            }
        })



    }



    override fun apiFunc(): suspend () -> IResp<*> {
        return { NetEngine.service.memberAddressList(10,repository().page) }

    }






}
